<h1 class="text-center"><?php echo __("Live Score"); ?></h1>

          <div id="webroot" data-url='<?php echo $this->webroot; ?>' ></div>
          
                <div id="tournament-template" class="tournament hidden container-fluid">
                        <div class="header-tournament-live row">
                            <div class="country col-md-12"></div>
                        </div>
                        <div class="body-tournament-live row"></div>
                </div>
                <div id="match-template" class="match hidden container-fluid" data-static-id="">
                        <div class="header-match-live row">
                            <div class="time col-md-2"></div>
                            <div class="localteam text-right col-md-3"><a class="team-popover"></a></div>
                            <div class="score col-md-2"></div>
                            <div class="visitorteam text-left col-md-3"><a class="team-popover"></a></div>
                            <div class="date col-md-2"></div>
                        </div>
                        <div class="body-match-live" style="display:none;"></div>
                </div>
                <div id="event-template" class="event hidden">
                </div>
                <div id="event-row-template" class="event-row row">
                  <div class="tdMinute col-md-2"><i class="fa-time"></i></div>
                  <div class="tdlocalteam col-md-3"></div>
                  <div class="tdScore col-md-2"></div>
                  <div class="tdvisitorteam col-md-3"></div>
                  <div class="empty col-md-2"></div>
                </div>
                <table id="lineups-template" class="table table-hover hidden">
                      <thead>
                        <tr>
                          <th><?php echo __("Numero"); ?></th>
                          <th><?php echo __("Giocatore"); ?></th>
                        </tr>
                      </thead>
                      <tbody>
                            <tr id="lineups-row-template"><td class="lineups-number"></td><td class="lineups-player"></td></tr>
                      </tbody>
                </table>  
                
                
				<button id="start-stop" data-action="stop" class="btn btn-mini pull-right" style="margin-right: 20px;">Start/Stop <span id='countdown' class="badge">0</span></button>
                
				<div id="controls">
					<input type="radio" name="period" value="168" checked="cheecked" /> <?php echo __("Ultima Settimana"); ?>
					<input type="radio" name="period" value="next" /> <?php echo __("Prossimo Calendario"); ?>
				</div>
                    
                <div id="tournaments" class="" data-country='<?php echo $country; ?>' ></div>


<script>

    var countdown = new Countdown($('#countdown'),59,refresh);
    var countdownTimer = $.timer(function() {countdown.execute();},1000,true);

    $(document).ready(function() {
        // var interval = 1000 * 20; // where X is your every X seconds
        refresh();
        $('#start-stop').click(function(){
            if ($('#start-stop').data('action')=='stop') {
                countdownTimer.pause();
                $('#start-stop').data('action','start');
            } else {
                countdownTimer.play();
                $('#start-stop').data('action','stop');
            }
        });
        
        $('input[name="period"]:radio').change(function() {
	        	refresh();
        });
        
        $(document).on('click', ".header-match-live", function() {
           $(this).next().slideToggle("fast");
        });

    });
    
    function refresh() {
    	  // console.log(nextCalendar);
          country = $('#tournaments').data('country');
          url = null;
          nextCalendar=$("input[name='period']:checked").val()=='next';
          if (nextCalendar)
	          url = $('#webroot').data('url')+'Feed/getLiveScore/'+country+'_shedule';
          else
	          url = $('#webroot').data('url')+'Feed/getLiveScore/'+country;
    	  
              $.ajax({ type: "GET", url: url
                , dataType: "xml"
                , success: function(xml) {
                    //console.log('refresh');
                    $('#tournaments').empty();
                    $(xml).find('category').each(function() {
                        writeTournament($(this));
                    });
                    // aggiungo i commenti dove trovo le informazioni della formazione e le statistiche
                    // addCommentaries(country);
                }
                , error: function(request, error, tipo_errore) { setFlash(error+': '+ tipo_errore, 'error'); }
              });
    	  
    }

	function addCommentaries(country) {
            // recupero altre infomrazioni inerenti alla squadra per il match corrente
            $.ajax({ type: "GET", url: "<?php echo $this -> webroot; ?>Feed/getCommentaries/"+country
                , dataType: "json"
                , success: function(data) {
                    if(data.success) {
                          $.ajax({ type: "GET", url: data.url
                            , dataType: "xml"
                            , success: function(xml) {
                                console.log('getCommentaries');
                              $(xml).find('match').each(function() {
                                writeLineups($(this));
                              });
                            }
                            , error: function(request, error, tipo_errore) { setFlash(error+': '+ tipo_errore, 'error'); }
                          });
                    } else
                        setFlash(data.message, data.level);
                }
            });
	}    
    
    function lastMatchs(formatted_date) {
        var t_date = new Date(formatted_date.replace(/(\d{2})\.(\d{2})\.(\d{4})/,'$3-$2-$1'));
        var today=new Date();
        var ore = $("input[name='period']:checked").val();
        if (!$.isNumeric(ore))
        	ore = 0;
        var ventiquattroOre = 1000*60*60*ore;
        var yesterday=today.getTime() - ventiquattroOre;
        // console.log(yesterday + ' - ' + t_date.getTime());
        // console.log(yesterday <= t_date.getTime());
        return (yesterday <= t_date.getTime());
    }

    
    function writeTournament(tournament) {
        if (lastMatchs(tournament.find('matches').attr('formatted_date'))) {
            tournamentElement = $('#tournament-template').clone();
            HeaderTournamentElement = tournamentElement.children('.header-tournament-live');
            HeaderTournamentElement.children('.country').html(tournament.attr('name'));
            HeaderTournamentElement.children('.date').html(tournament.find('matches').attr('formatted_date'));
            tournament.find('match').each(function() {
                if (lastMatchs($(this).attr('formatted_date')))
                    tournamentElement.children('.body-tournament-live').append(writeMatch($(this)));
            });
            tournamentElement.removeAttr('id');
            tournamentElement.removeClass('hidden');
            tournamentElement.appendTo($('#tournaments'));
        }
    }
    
    function writeMatch(match) {
        matchElement = $('#match-template').clone();
        matchElement.attr('id','match'+match.attr('static_id'));
        localteam = match.find('localteam');
        visitorteam = match.find('visitorteam');
        // console.log(match.attr('static_id'));
        matchElement.data('static-id', match.attr('static_id'));
        // console.log(matchElement.data('static-id'));
        matchElement.children('.header-match-live').children('.localteam').children('a').html(localteam.attr('name'));
        matchElement.children('.header-match-live').children('.score').html('[' + localteam.attr('goals') + ' - ' + visitorteam.attr('goals') + ']');
        matchElement.children('.header-match-live').children('.visitorteam').children('a').html(visitorteam.attr('name'));
        matchElement.children('.header-match-live').children('.time').html(match.attr('time') + ' (' + match.attr('status') + ')');
        matchElement.children('.header-match-live').children('.date').html(match.attr('formatted_date'));
        eventElement = $('#event-template').clone();
        match.find('event').each(function() {
            writeEvent(eventElement,$(this));
        });
        matchElement.children('.body-match-live').append(eventElement);
        eventElement.removeAttr('id');
        eventElement.removeClass('hidden');
        // matchElement.removeAttr('id');
        matchElement.removeClass('hidden');
        return matchElement;
    }

    function writeEvent(eventElement, eventData) {
        // console.log(eventData);
        eventRowElement = $('#event-row-template').clone();
        // console.log(eventElement.find('tr').html());
        eventRowElement.children('.td'+eventData.attr('team')).html('<div class="'+eventData.attr('type')+" "+eventData.attr('team')+'"></div> ' + eventData.attr('player'));
        eventRowElement.children('.tdMinute').html("<i class='fa-clock-o'></i> "+eventData.attr('minute')+"'");
        eventRowElement.children('.tdScore').html(eventData.attr('result'));
        eventRowElement.removeAttr('id');
        eventRowElement.removeClass('hidden');
        eventElement.append(eventRowElement);
        // return eventElement;
    }

    function writeLineups(match) {
        lineupsElement = $('#lineups-template').clone();
        // console.log(eventElement.find('tr').html());
        lineupsElement.children('.td'+eventData.attr('team')).html(eventData.attr('type') + ' ' + eventData.attr('player'));
        lineupsElement.children('.tdMinute').html(eventData.attr('minute')+"'");
        lineupsElement.children('.tdScore').html(eventData.attr('result'));
        lineupsElement.removeAttr('id');
        lineupsElement.removeClass('hidden');
        matchElement = $('#match'+match.attr('static_id'));
        matchElement.children('.body-match-live').append(lineupsElement);
        // return eventElement;
    }

</script>